package com.qulai.web.controller.basic;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qulai.amazon_us.domain.basic.Image;
import com.qulai.amazon_us.domain.basic.dto.ImageDto;
import com.qulai.amazon_us.service.basic.IImageService;
import com.qulai.common.annotation.Log;
import com.qulai.common.core.controller.BaseController;
import com.qulai.common.core.domain.AjaxResult;
import com.qulai.common.core.page.TableDataInfo;
import com.qulai.common.enums.BusinessType;
import com.qulai.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 商品图片Controller
 *
 * @author hunan
 * @date 2025-01-08
 */
@RestController
@RequestMapping("/basic/image")
public class ImageController extends BaseController {
    @Autowired
    private IImageService imageService;


    /**
     * 查询商品图片列表
     */
    @PreAuthorize("@ss.hasPermi('basic:image:list')")
    @GetMapping("/list")
    public TableDataInfo list(ImageDto image) {
        if (image.getParams() != null && null != image.getParams().get("beginId")) {
            image.setId(null);
        }
        startPage();
        List<Image> list = imageService.selectImageList(image);
        //暂时清理一些数据
        for (int i = 0; i < list.size(); i++) {
            Image tmp = list.get(i);

            tmp.setMainImage(tmp.getMainImage() == null ? "" : tmp.getMainImage() + "?len=" + countNonEmptyImageUrls(tmp));
            tmp.setOtherImageUrl1("");
            tmp.setOtherImageUrl2("");
            tmp.setOtherImageUrl3("");
            tmp.setOtherImageUrl4("");
            tmp.setOtherImageUrl5("");
            tmp.setOtherImageUrl6("");
            tmp.setOtherImageUrl7("");
            tmp.setOtherImageUrl8("");
            tmp.setOtherImageUrl9("");
            tmp.setOtherImageUrl10("");
            tmp.setOtherImageUrl11("");
            tmp.setOtherImageUrl12("");
            tmp.setOtherImageUrl13("");
            tmp.setOtherImageUrl14("");
            tmp.setOtherImageUrl15("");
            if (Objects.nonNull(tmp.getOcrResult()) && !tmp.getOcrResult().isEmpty()) {
                try {
                    JSONObject ocrJson = JSON.parseObject(tmp.getOcrResult());
                    JSONArray hitWord = ocrJson.getJSONArray("hit_word");
                    if (Objects.nonNull(hitWord)) {
                        String show = hitWord.get(0).toString().replace("apiocr_", "");

                        if (show.contains("图10")) {
                            show = show.replace("图10", "副图9");
                        } else if (show.contains("图11")) {
                            show = show.replace("图11", "副图10");
                        } else if (show.contains("图12")) {
                            show = show.replace("图12", "副图11");
                        } else if (show.contains("图13")) {
                            show = show.replace("图13", "副图12");
                        } else if (show.contains("图14")) {
                            show = show.replace("图14", "副图13");
                        } else if (show.contains("图15")) {
                            show = show.replace("图15", "副图14");
                        } else if (show.contains("图16")) {
                            show = show.replace("图16", "副图15");
                        } else if (show.contains("图2")) {
                            show = show.replace("图2", "尺寸图");
                        } else if (show.contains("图3")) {
                            show = show.replace("图3", "副图2");
                        } else if (show.contains("图4")) {
                            show = show.replace("图4", "副图3");
                        } else if (show.contains("图5")) {
                            show = show.replace("图5", "副图4");
                        } else if (show.contains("图6")) {
                            show = show.replace("图6", "副图5");
                        } else if (show.contains("图7")) {
                            show = show.replace("图7", "副图6");
                        } else if (show.contains("图8")) {
                            show = show.replace("图8", "副图7");
                        } else if (show.contains("图9")) {
                            show = show.replace("图9", "副图8");
                        } else if (show.contains("图1")) {
                            show = show.replace("图1", "主图");
                        }

                        tmp.setOcrResult(show + "  详情请点“修改”查看");

                    } else {
                        tmp.setOcrResult("-");
                    }
                } catch (Exception e) {
                }
            }

        }
        return getDataTable(list);
    }

    /**
     * 导出商品图片列表
     */
    @PreAuthorize("@ss.hasPermi('basic:image:export')")
    @Log(title = "商品图片", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ImageDto image) {
        List<Image> list = imageService.selectImageList(image);
        ExcelUtil<Image> util = new ExcelUtil<Image>(Image.class);
        util.exportExcel(response, list, "商品图片数据");
    }

    private int countNonEmptyImageUrls(Image tmp) {
        int count = 0;
        if (!tmp.getMainImage().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl1().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl2().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl3().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl4().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl5().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl6().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl7().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl8().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl9().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl10().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl11().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl12().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl13().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl14().trim().isEmpty()) count++;
        if (!tmp.getOtherImageUrl15().trim().isEmpty()) count++;

        return count;
    }

    /**
     * 获取商品图片详细信息
     */
    @PreAuthorize("@ss.hasPermi('basic:image:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Image image = imageService.selectImageById(id);
        int i = countNonEmptyImageUrls(image);
        image.setMainImage(Objects.equals(image.getMainImage(), "") ? "" : image.getMainImage().contains("?len=") ? image.getMainImage() : image.getMainImage() + "?len=" + i);
        image.setOtherImageUrl1(Objects.equals(image.getOtherImageUrl1(), "") ? "" : image.getOtherImageUrl1().contains("?len=") ? image.getOtherImageUrl1() : image.getOtherImageUrl1() + "?len=" + i);
        image.setOtherImageUrl2(Objects.equals(image.getOtherImageUrl2(), "") ? "" : image.getOtherImageUrl2().contains("?len=") ? image.getOtherImageUrl2() : image.getOtherImageUrl2() + "?len=" + i);
        image.setOtherImageUrl3(Objects.equals(image.getOtherImageUrl3(), "") ? "" : image.getOtherImageUrl3().contains("?len=") ? image.getOtherImageUrl3() : image.getOtherImageUrl3() + "?len=" + i);
        image.setOtherImageUrl4(Objects.equals(image.getOtherImageUrl4(), "") ? "" : image.getOtherImageUrl4().contains("?len=") ? image.getOtherImageUrl4() : image.getOtherImageUrl4() + "?len=" + i);
        image.setOtherImageUrl5(Objects.equals(image.getOtherImageUrl5(), "") ? "" : image.getOtherImageUrl5().contains("?len=") ? image.getOtherImageUrl5() : image.getOtherImageUrl5() + "?len=" + i);
        image.setOtherImageUrl6(Objects.equals(image.getOtherImageUrl6(), "") ? "" : image.getOtherImageUrl6().contains("?len=") ? image.getOtherImageUrl6() : image.getOtherImageUrl6() + "?len=" + i);
        image.setOtherImageUrl7(Objects.equals(image.getOtherImageUrl7(), "") ? "" : image.getOtherImageUrl7().contains("?len=") ? image.getOtherImageUrl7() : image.getOtherImageUrl7() + "?len=" + i);
        image.setOtherImageUrl8(Objects.equals(image.getOtherImageUrl8(), "") ? "" : image.getOtherImageUrl8().contains("?len=") ? image.getOtherImageUrl8() : image.getOtherImageUrl8() + "?len=" + i);
        image.setOtherImageUrl9(Objects.equals(image.getOtherImageUrl9(), "") ? "" : image.getOtherImageUrl9().contains("?len=") ? image.getOtherImageUrl9() : image.getOtherImageUrl9() + "?len=" + i);
        image.setOtherImageUrl10(Objects.equals(image.getOtherImageUrl10(), "") ? "" : image.getOtherImageUrl10().contains("?len=") ? image.getOtherImageUrl10() : image.getOtherImageUrl10() + "?len=" + i);
        image.setOtherImageUrl11(Objects.equals(image.getOtherImageUrl11(), "") ? "" : image.getOtherImageUrl11().contains("?len=") ? image.getOtherImageUrl11() : image.getOtherImageUrl11() + "?len=" + i);
        image.setOtherImageUrl12(Objects.equals(image.getOtherImageUrl12(), "") ? "" : image.getOtherImageUrl12().contains("?len=") ? image.getOtherImageUrl12() : image.getOtherImageUrl12() + "?len=" + i);
        image.setOtherImageUrl13(Objects.equals(image.getOtherImageUrl13(), "") ? "" : image.getOtherImageUrl13().contains("?len=") ? image.getOtherImageUrl13() : image.getOtherImageUrl13() + "?len=" + i);
        image.setOtherImageUrl14(Objects.equals(image.getOtherImageUrl14(), "") ? "" : image.getOtherImageUrl14().contains("?len=") ? image.getOtherImageUrl14() : image.getOtherImageUrl14() + "?len=" + i);
        image.setOtherImageUrl15(Objects.equals(image.getOtherImageUrl15(), "") ? "" : image.getOtherImageUrl15().contains("?len=") ? image.getOtherImageUrl15() : image.getOtherImageUrl15() + "?len=" + i);
        return success(image);
    }

    /**
     * 新增商品图片
     */
    @PreAuthorize("@ss.hasPermi('basic:image:add')")
    @Log(title = "商品图片", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Image image) {
        return toAjax(imageService.insertImage(image));
    }

    /**
     * 修改商品图片
     */

    @PreAuthorize("@ss.hasPermi('basic:image:edit')")
    @Log(title = "商品图片", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Image image) {
        // 处理 mainImage
        image.setMainImage(truncateAtQuestionMark(image.getMainImage()));

        // 处理 otherImageUrl1 到 otherImageUrl15
        image.setOtherImageUrl1(truncateAtQuestionMark(image.getOtherImageUrl1()));
        image.setOtherImageUrl2(truncateAtQuestionMark(image.getOtherImageUrl2()));
        image.setOtherImageUrl3(truncateAtQuestionMark(image.getOtherImageUrl3()));
        image.setOtherImageUrl4(truncateAtQuestionMark(image.getOtherImageUrl4()));
        image.setOtherImageUrl5(truncateAtQuestionMark(image.getOtherImageUrl5()));
        image.setOtherImageUrl6(truncateAtQuestionMark(image.getOtherImageUrl6()));
        image.setOtherImageUrl7(truncateAtQuestionMark(image.getOtherImageUrl7()));
        image.setOtherImageUrl8(truncateAtQuestionMark(image.getOtherImageUrl8()));
        image.setOtherImageUrl9(truncateAtQuestionMark(image.getOtherImageUrl9()));
        image.setOtherImageUrl10(truncateAtQuestionMark(image.getOtherImageUrl10()));
        image.setOtherImageUrl11(truncateAtQuestionMark(image.getOtherImageUrl11()));
        image.setOtherImageUrl12(truncateAtQuestionMark(image.getOtherImageUrl12()));
        image.setOtherImageUrl13(truncateAtQuestionMark(image.getOtherImageUrl13()));
        image.setOtherImageUrl14(truncateAtQuestionMark(image.getOtherImageUrl14()));
        image.setOtherImageUrl15(truncateAtQuestionMark(image.getOtherImageUrl15()));
        return toAjax(imageService.updateImage(image));
    }


    // 处理单个字段的公共方法
    private String truncateAtQuestionMark(String url) {
        // 检查 null 或空字符串
        if (url == null || url.isEmpty()) {
            return "";
        }
        // 如果包含“?”，只保留“?”前面的部分
        if (url.contains("?")) {
            return url.substring(0, url.indexOf("?"));
        }
        // 否则保持原样
        return url;
    }

//    /**
//     * 下线商品图片,这里设置为问题商品
//     */
//    @PreAuthorize("@ss.hasPermi('basic:image:remove')")
//    @Log(title = "商品图片", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids) {
//        return toAjax(imageService.deleteImageByIds(ids));
//    }


    /**
     * 批量下线商品图片
     */
    @PreAuthorize("@ss.hasPermi('basic:image:edit')")
    @Log(title = "商品图片", businessType = BusinessType.UPDATE)
    @PutMapping("/batchOffLine_logo/{ids}")
    public AjaxResult batchOffLineLogo(@PathVariable Long[] ids) {
        String optName = getUsername();
        return toAjax(imageService.batchOffLineByIds(ids, optName, 2));
    }

    @PreAuthorize("@ss.hasPermi('basic:image:edit')")
    @Log(title = "商品图片", businessType = BusinessType.UPDATE)
    @PutMapping("/batchOffLine_prod/{ids}")
    public AjaxResult batchOffLineProd(@PathVariable Long[] ids) {
        String optName = getUsername();
        return toAjax(imageService.batchOffLineByIds(ids, optName, 5));
    }


    /**
     * 批量通过商品图片
     */
    @PreAuthorize("@ss.hasPermi('basic:image:edit')")
    @Log(title = "商品图片", businessType = BusinessType.UPDATE)
    @PutMapping("/batchAccess/{ids}")
    public AjaxResult batchAccess(@PathVariable Long[] ids) {
        String optName = getUsername();
        return toAjax(imageService.batchAccessByIds(ids, optName));
    }
}
